import React, { useMemo, useState } from "react";
import { Drawer, Form, Space, Button, message } from "antd";
import FormRender from '@/components/FormRender';
import { getBusinessConfig } from './metaData';

interface Props {
  id?: number | null
  businessType: 'invation' | 'visited' | 'signed' | 'loan'
  isShow: boolean
  editItem: any
  onCancel: (...agrs: any[]) => void
  onFinish: () => void
  setEditItem: ({ }) => void
}

export default function BusinessActionDrawer({ businessType, isShow, onCancel, editItem = {}, setEditItem, onFinish }: Props) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const businessConfig = useMemo<any>(() => getBusinessConfig({ businessType, editItem }), [businessType, editItem])

  const submit = async () => {
    const values = await form.validateFields();

    if (!values) return;

    let params = {
      ...businessConfig?.reqFixParams,
      ...values,
    };
    setLoading(true);
    businessConfig?.submitFn(params).then((data) => {
      setLoading(false);
      if (!data) return;
      message.success(`${businessConfig?.title}成功`);
      onClose();
      onFinish?.();
    })
      .catch((err) => {
        throw (err)
      });
  };

  const onClose = () => {
    form?.resetFields();
    onCancel(false);
    setEditItem?.({});
  };

  return (
    <Drawer
      maskClosable={false}
      title={businessConfig?.title}
      destroyOnClose={true}
      open={isShow}
      width={720}
      onClose={onClose}
      extra={
        <Space>
          <Button onClick={onClose}>关闭</Button>
          <Button onClick={submit} type="primary" loading={loading}>
            提交
          </Button>
        </Space>
      }
    >
      <FormRender
        defaultData={{}}
        form={form}
        formItem={businessConfig?.formList || []}
      />
    </Drawer>
  );
}